﻿
#if !SILVERLIGHT
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EffiProz.Core.Lib;
using EffiProz.Core.DataTypes;
using EffiProz.Core.Errors;
using EffiProz.Core.Persist;

namespace EffiProz.Core.RowIO
{
    public class RowOutputBinaryEncode : RowOutputBinary
    {
        Crypto crypto;

        public RowOutputBinaryEncode(Crypto crypto, int initialSize, int scale)
            : base(initialSize, scale)
        {

            this.crypto = crypto;
        }

        public override void writeData(Object[] data, SqlType[] types)
        {

            if (crypto == null)
            {
                base.writeData(data, types);
            }
            else
            {
                int start = count;

                writeInt(0);
                base.writeData(data, types);

                int origLength = count - start - INT_STORE_SIZE;
                byte[] encoded = crypto.encode(buf, start + INT_STORE_SIZE,
                                              origLength);
                int newLength = encoded.Length;
                Array.Copy(encoded, 0, buf, start + INT_STORE_SIZE, newLength);

                writeIntData(newLength, start);

                count = start + INT_STORE_SIZE + newLength;
            }
        }

        /**
         *  Calculate the size of byte array required to store a row.
         *
         * @param  row - a database row
         * @return  size of byte array
         * @exception  CoreException When data is inconsistent
         */
        public override int getSize(Row row)
        {

            int size = base.getSize(row);

            if (crypto != null)
            {
                size = crypto.getEncodedSize(size - INT_STORE_SIZE)
                       + INT_STORE_SIZE * 2;
            }

            return size;
        }
    }
}

#endif
